//
//  GridController.m
//  FirstGridApp
//
//  Created by Andrew Spina on 4/10/10.
//  Copyright 2010 STScI. All rights reserved.
//

#import "GridController.h"

@implementation GridController

@synthesize gridScrollView;
@synthesize masterView;
// A double array of Strings. A light weight datamodel.
@synthesize map;
@synthesize buttons;
// This stores the first button that the user taps. The second button will swap with it.
//@synthesize activeToken;
@synthesize activeTokenLocation;
@synthesize buttonToPointDict;

const CGFloat kScrollObjHeight    = 640;
const CGFloat kScrollObjWidth    = 480;

// TODO migrate these fields and map into a data class.
const CGFloat cell_dim   = 20;
const CGFloat cell_x_off = 9;
const CGFloat cell_y_off = -1;
const int cell_count_x = 31;
const int cell_count_y = 39;
const CGFloat initial_zoom = 2.5;

- (NSString*) textAtPoint: (Point2d *) point {
	NSString *text = [[map objectAtIndex:point.x] objectAtIndex:point.y];
	return text;
}

- (void) setTextAtPoint: (Point2d *) point newText: (NSString *) text{
	[[map objectAtIndex:point.x] replaceObjectAtIndex:point.y withObject:text];
	[ [[buttons objectAtIndex:point.x] objectAtIndex:point.y] setTitle:text forState:UIControlStateNormal];
}

- (Point2d*) pointForButton: (UIButton *) button {
	return [self.buttonToPointDict objectForKey:[NSValue valueWithPointer:button]];
}

- (UIButton *) buttonAtX: (int) x andY: (int) y {
	return [[buttons objectAtIndex:x] objectAtIndex:y];	
}

- (UIButton *) buttonAtPoint: (Point2d *) point {
	return [self buttonAtX: point.x andY:point.y];
}

- (bool) isToken: (NSString *) tokenText {
	return ! [tokenText isEqualToString:@""];
}

- (bool) isTokenAtPoint: (Point2d *) point {
	return [self isToken: [self textAtPoint:point]];
}

- (void) loadMapData {
	self.map = [NSMutableArray arrayWithCapacity:cell_count_x];
	for (int x = 0; x <= cell_count_x; x++){
		[map insertObject:[NSMutableArray arrayWithCapacity:cell_count_y] atIndex:x];
		for (int y = 0; y <= cell_count_y; y++){
//			NSString *value = [NSString stringWithFormat:@"%d", (x + y)];
			NSString *value = @"";
			if(x % 3 == 0 && y % 3 == 0) {
				value = [NSString stringWithFormat:@"%d, %d", x, y];
			}
			[value retain];
			[[map objectAtIndex:x] insertObject:value atIndex:y];
		}
	}
}

// Rest State means that the user hasn't yet selected an active token.
- (void) setButtonToRestState: (UIButton *) button {
	button.backgroundColor = [UIColor clearColor];
	[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	[button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
	button.titleLabel.font = [UIFont systemFontOfSize: 7];
	NSString * buttonText = [self textAtPoint:[self pointForButton:button]];
	if( ! [self isToken: buttonText] ){
		button.alpha = .05;
		[button setEnabled:NO];
	} else {
		[button setEnabled:YES];
		button.alpha = .5;
	}
	[button setTitle:buttonText forState:UIControlStateNormal];
	[button setTitle:@"" forState:UIControlStateApplication];
}

- (UIButton*) createNewButtonForX: (int)x andY: (int)y {
	UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	button.frame = CGRectMake(x*cell_dim + cell_x_off, y*cell_dim + cell_y_off, cell_dim, cell_dim); // size and position of button
	[button addTarget:self action:@selector(cellTapped:) forControlEvents:UIControlEventTouchDown];
	[self.buttonToPointDict setObject: [Point2d createPointAtX:x andY:y] forKey:[NSValue valueWithPointer:button]];
	[self setButtonToRestState:button];
	return button;
}

- (void) addMarkerButtons {
	self.buttonToPointDict = [[NSMutableDictionary alloc] init];
	self.buttons = [NSMutableArray arrayWithCapacity:cell_count_x];
	for (int x = 0; x <= cell_count_x; x++){
		[buttons insertObject:[NSMutableArray arrayWithCapacity:cell_count_y] atIndex:x];
		for (int y = 0; y <= cell_count_y; y++){
			UIButton *button = [self createNewButtonForX:x andY:y];
			[[buttons objectAtIndex:x] insertObject:button atIndex:y];
			[self.masterView addSubview:button];
		}
	}
}

- (void) configureMasterView {
	UIImage *image = [UIImage imageNamed:@"map.jpg"];
	UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
	self.masterView = [UIView alloc];
	[masterView initWithFrame:imageView.frame];
	[masterView addSubview:imageView];
	[self addMarkerButtons];
	//[imageView release];
}

- (void) configureScrollView {
	[self.gridScrollView addSubview:masterView];
	[self.gridScrollView setZoomScale:initial_zoom animated:NO];
	[self.gridScrollView setContentSize:CGSizeMake(masterView.bounds.size.height, masterView.bounds.size.width)];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	[self loadMapData];
	[self configureMasterView];
	[self configureScrollView];	
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
	return masterView;
}

- (void) setButtonToActiveState: (UIButton *) button {
	if([self isToken:[self textAtPoint:[self pointForButton:button]]]){
		[button setEnabled:NO];
		button.alpha = .25;
	} else {
		[button setEnabled:YES];
		//button.alpha = .5;
	}
}

- (void) updateForNewActiveToken: (UIButton *) token {
	token.alpha = 1;
	for (int x = 0; x <= cell_count_x; x++){
		for (int y = 0; y <= cell_count_y; y++){
			UIButton * buttonAtPoint = [self buttonAtX:x andY:y];
			if(buttonAtPoint != token) {
				[self setButtonToActiveState:buttonAtPoint];
			}
		}
	}
}

- (void) returnToRestState {
	for (int x = 0; x <= cell_count_x; x++){
		for (int y = 0; y <= cell_count_y; y++){
			[self setButtonToRestState:[self buttonAtX:x andY:y]];
		}
	}
}

- (void) cellTapped: (id) tapId {
	UIButton *button = (UIButton*) tapId;
	Point2d *tappedPoint = [self pointForButton:button];
	if(self.activeTokenLocation == nil) {
		// Do do anything if the first tap isn't on a token.
		if([self isTokenAtPoint:tappedPoint]){
			self.activeTokenLocation = tappedPoint;
			[self updateForNewActiveToken: button];
		}
	} else {
		if(![self isTokenAtPoint:tappedPoint] || tappedPoint == self.activeTokenLocation){
			Point2d * secondTapLocation = tappedPoint;
			NSString *textAtSecondTap = [self textAtPoint:secondTapLocation];
			NSString *originText = [self textAtPoint:self.activeTokenLocation];
			[self setTextAtPoint:secondTapLocation newText:originText];
			[self setTextAtPoint:self.activeTokenLocation newText:textAtSecondTap];
			[self returnToRestState];
			self.activeTokenLocation = nil;
		}
	}
}

- (void)dealloc {
    [super dealloc];
	[masterView dealloc];
}


@end
